package cube.utils.exec;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import cube.utils.BaseUtil;

/**
 * 系统命令执行器
 * 
 * @author abiao
 */
public class CmdExecutor {

    /**
     * 命令执行线程
     */
    private Thread cmdThread;
    private Process p;

    /**
     * 中断标记
     */
    private boolean stop;
    private BufferedReader br;

    /**
     * 非阻塞执行命令
     */
    public void execute(final String cmd) {
        cmdThread = new Thread() {
            public void run() {
                blockExecute(cmd);
            }
        };
        cmdThread.start();
    }

    /**
     * 阻塞执行命令，直到命令执行完毕
     */
    public void blockExecute(String cmd) {
        blockExecute(cmd, 0);
    }

    /**
     * 阻塞执行命令，直到命令执行完毕
     */
    public void blockExecute(String cmd, int timeout) {
        Timer timer = timerStart(timeout);
        executeCommand(cmd.trim().split(" "));
        commandTerminate();
        timerTerminate(timer);
    }

    /**
     * 终止计时器
     */
    private void timerTerminate(Timer timer) {
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 启动超时线程
     */
    private Timer timerStart(int timeout) {
        Timer timer = null;
        if (timeout > 0) {
            TimerTask task = new TimerTask() {
                public void run() {
                    commandTerminate();
                }
            };
            timer = new Timer();
            timer.schedule(task, timeout);
        }
        return timer;
    }

    /**
     * 命令处理与执行
     */
    private void executeCommand(String[] cmd) {
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        try {
            p = pb.start();
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String result = null;
            while (!stop && (result = br.readLine()) != null) {
                output(result);
            }
            p.waitFor();
        } catch (Exception e) {
        }
    }

    /**
     * 停止命令执行
     */
    public void stop() {
        commandTerminate();
    }

    /**
     * 销毁命令执行器，中断命令执行
     */
    private void commandTerminate() {
        try {
            this.stop = true;
            if (p != null) {
                p.destroy();
            }
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            BaseUtil.log.error(e.getMessage());
        }
    }

    /**
     * 命令执行结果输出
     */
    public void output(String result) {
    }
}
